package crp.extensions.scy.storage;

import com.qwlabs.storage.s3.S3Config;
import crp.core.resource.app.ResourceService;
import crp.core.shared.Configs;
import crp.extensions.scy.SCY;
import crp.extensions.scy.repositories.SCYResourceSpaceRepository;
import io.quarkus.arc.lookup.LookupIfProperty;
import org.eclipse.microprofile.config.inject.ConfigProperty;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.CDI;
import java.util.Optional;

import static com.qwlabs.storage.s3.S3StorageHelper.createS3Client;

@Dependent
public class SCYStorageBootstrap {

    public static final String ENABLED = "app.storage.scy.enabled";
    private static final String REGION = "app.storage.scy.region";
    private static final String URL = "app.storage.scy.url";
    private static final String ACCESS_KEY = "app.storage.scy.access-key";
    private static final String SECRET_KEY = "app.storage.scy.secret-key";

    @Produces
    @ApplicationScoped
    @LookupIfProperty(name = Configs.KEY_APP_ENV, stringValue = SCY.ENV)
    @LookupIfProperty(name = ENABLED, stringValue = "true")
    public SCYResourceSynchronizer produceResourceSynchronizer(ResourceService resourceService,
                                                               SCYResourceSpaceRepository resourceSpaceRepository) {
        SCYStorageEngine storageEngine = CDI.current().select(SCYStorageEngine.class).get();
        return new SCYResourceSynchronizer(storageEngine, resourceService, resourceSpaceRepository);
    }


    @Produces
    @ApplicationScoped
    @LookupIfProperty(name = Configs.KEY_APP_ENV, stringValue = SCY.ENV)
    @LookupIfProperty(name = ENABLED, stringValue = "true")
    public SCYStorageEngine produceStorageEngine(@ConfigProperty(name = REGION) Optional<String> region,
                                                 @ConfigProperty(name = URL) Optional<String> url,
                                                 @ConfigProperty(name = ACCESS_KEY) Optional<String> accessKey,
                                                 @ConfigProperty(name = SECRET_KEY) Optional<String> secretKey) {
        return new SCYStorageEngine(
                createS3Client(S3Config.builder()
                        .url(url.orElse(null))
                        .region(region.orElse(null))
                        .accessKey(accessKey.orElse(null))
                        .secretKey(secretKey.orElse(null))
                        .build())
        );
    }
}
